import 'package:flutter/material.dart';

class CartPage extends StatefulWidget {
  const CartPage({Key? key}) : super(key: key);

  @override
  State<CartPage> createState() => _CartPageState();
}

class _CartPageState extends State<CartPage> {
  final List<CartItem> _cartItems = List.generate(
    5,
    (index) => CartItem(
      id: index,
      name: '商品${index + 1}',
      price: (index + 1) * 100.0,
      count: 1,
      isSelected: true,
    ),
  );

  bool _isAllSelected = true;

  @override
  Widget build(BuildContext context) {
    double totalPrice = _calculateTotalPrice();
    
    return Scaffold(
      appBar: AppBar(
        title: const Text('购物车'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: _cartItems.isEmpty
          ? const Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.shopping_cart_outlined, size: 80, color: Colors.grey),
                  SizedBox(height: 16),
                  Text('购物车空空如也，去逛逛吧~', style: TextStyle(color: Colors.grey)),
                ],
              ),
            )
          : Column(
              children: [
                Expanded(
                  child: ListView.builder(
                    itemCount: _cartItems.length,
                    itemBuilder: (context, index) {
                      final item = _cartItems[index];
                      return Dismissible(
                        key: Key(item.id.toString()),
                        direction: DismissDirection.endToStart,
                        background: Container(
                          color: Colors.red,
                          alignment: Alignment.centerRight,
                          padding: const EdgeInsets.only(right: 16.0),
                          child: const Icon(Icons.delete, color: Colors.white),
                        ),
                        onDismissed: (direction) {
                          setState(() {
                            _cartItems.removeAt(index);
                          });
                          ScaffoldMessenger.of(context).showSnackBar(
                            SnackBar(content: Text('${item.name}已移除')),
                          );
                        },
                        child: Card(
                          margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                          child: Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Row(
                              children: [
                                Checkbox(
                                  value: item.isSelected,
                                  onChanged: (value) {
                                    setState(() {
                                      item.isSelected = value!;
                                      _updateAllSelectedState();
                                    });
                                  },
                                ),
                                Container(
                                  width: 80,
                                  height: 80,
                                  color: Colors.grey[200],
                                  child: const Icon(Icons.image, color: Colors.grey),
                                ),
                                const SizedBox(width: 12),
                                Expanded(
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        item.name,
                                        style: const TextStyle(fontWeight: FontWeight.bold),
                                      ),
                                      const SizedBox(height: 4),
                                      Text(
                                        '规格: 默认',
                                        style: TextStyle(color: Colors.grey[600], fontSize: 12),
                                      ),
                                      const SizedBox(height: 8),
                                      Text(
                                        '¥${item.price.toStringAsFixed(2)}',
                                        style: TextStyle(
                                          color: Theme.of(context).primaryColor,
                                          fontWeight: FontWeight.bold,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                                Row(
                                  children: [
                                    IconButton(
                                      icon: const Icon(Icons.remove_circle_outline),
                                      onPressed: item.count > 1
                                          ? () {
                                              setState(() {
                                                item.count--;
                                              });
                                            }
                                          : null,
                                    ),
                                    Text('${item.count}'),
                                    IconButton(
                                      icon: const Icon(Icons.add_circle_outline),
                                      onPressed: () {
                                        setState(() {
                                          item.count++;
                                        });
                                      },
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        ),
                      );
                    },
                  ),
                ),
                Container(
                  padding: const EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    boxShadow: [
                      BoxShadow(
                        color: Colors.grey.withOpacity(0.3),
                        spreadRadius: 1,
                        blurRadius: 5,
                        offset: const Offset(0, -3),
                      ),
                    ],
                  ),
                  child: Row(
                    children: [
                      Checkbox(
                        value: _isAllSelected,
                        onChanged: (value) {
                          setState(() {
                            _isAllSelected = value!;
                            for (var item in _cartItems) {
                              item.isSelected = _isAllSelected;
                            }
                          });
                        },
                      ),
                      const Text('全选'),
                      const Spacer(),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.end,
                        children: [
                          Text(
                            '合计: ¥${totalPrice.toStringAsFixed(2)}',
                            style: TextStyle(
                              color: Theme.of(context).primaryColor,
                              fontWeight: FontWeight.bold,
                              fontSize: 16,
                            ),
                          ),
                          Text(
                            '已选${_getSelectedCount()}件商品',
                            style: TextStyle(color: Colors.grey[600], fontSize: 12),
                          ),
                        ],
                      ),
                      const SizedBox(width: 16),
                      ElevatedButton(
                        onPressed: _getSelectedCount() > 0
                            ? () {
                                // 结算逻辑
                                ScaffoldMessenger.of(context).showSnackBar(
                                  const SnackBar(content: Text('结算功能待实现')),
                                );
                              }
                            : null,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Theme.of(context).primaryColor,
                          foregroundColor: Colors.white,
                          padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                        ),
                        child: const Text('结算'),
                      ),
                    ],
                  ),
                ),
              ],
            ),
    );
  }

  double _calculateTotalPrice() {
    double total = 0;
    for (var item in _cartItems) {
      if (item.isSelected) {
        total += item.price * item.count;
      }
    }
    return total;
  }

  int _getSelectedCount() {
    int count = 0;
    for (var item in _cartItems) {
      if (item.isSelected) {
        count += item.count;
      }
    }
    return count;
  }

  void _updateAllSelectedState() {
    _isAllSelected = _cartItems.every((item) => item.isSelected);
  }
}

class CartItem {
  final int id;
  final String name;
  final double price;
  int count;
  bool isSelected;

  CartItem({
    required this.id,
    required this.name,
    required this.price,
    required this.count,
    required this.isSelected,
  });
}